<template>
  <div style="margin-top: 20px">
    <el-row :gutter="10">
      <el-col :span="18">
        <el-form ref="editForm" :model="form" label-width="150px">
          <el-form-item label="数据库" prop="DbId" :rules="[{required: true, message: '请输入'}]">
            <el-select v-model="form.DbId" @change="changeDb">
              <el-option
                v-for="item in DbList"
                :key="item.ReportDbId"
                :label="item.Name"
                :value="item.ReportDbId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="SQL" prop="AllSql" :rules="[{required: true, message: '请输入'}]">
            <el-button icon="el-icon-s-open" @click="beautifulSql" />
            <ace-editor ref="ace" :custom-complete-data="customCompleteData" @content-change="v=>this.form.AllSql=v" />
          </el-form-item>
          <el-form-item label="模糊搜索SQL" prop="FilterSql" :rules="[{required: true, message: '请输入'}]">
            <el-button icon="el-icon-s-open" @click="beautifulCountSql" />
            <ace-editor ref="ace2" :custom-complete-data="customCompleteData" @content-change="v=>this.form.FilterSql=v" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="save">
              保存
            </el-button>
            <el-button @click="close">
              取消
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="6">
        <el-select v-model="SelectTable" filterable placeholder="选择表">
          <el-option v-for="table in Tables" :key="table.Name" :label="table.Name" :value="table.Name" />
        </el-select>
        <el-table
          :data="columns"
          border
          fit
          highlight-current-row
          max-height="800px"
          style="width: 100%; margin-top: 20px"
        >
          <el-table-column label="字段" prop="Name" />
          <el-table-column label="备注" prop="Remark" />
        </el-table>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import commonValidator from '@/utils/commonValidator'
import gql from 'graphql-tag'
import apolloClient from '@/utils/graphql'
import sqlFormatter from 'sql-formatter'
import AceEditor from '@/components/AceEditor'
import { Parser } from 'node-sql-parser'
export default {
  name: 'DictCategoryEditSql',
  components: {
    AceEditor
  },
  props: {
    // id
    id: {
      type: String,
      required: false
    }
  },
  data() {
    return {
      // 表单数据
      form: {
        DbId: null,
        DictionarySqlId: null,
        AllSql: null,
        FilterSql: null
      },
      DbList: [],
      Tables: [],
      commonValidator,
      SelectTable: null,

      Parser: new Parser()
    }
  },
  computed: {
    customCompleteData() {
      var data = []
      const item = {}
      item.meta = '模糊搜索'
      item.caption = 'keyword'
      item.value = 'keyword'
      item.score = 200
      data.push(item)

      var columns = []
      if (this.Tables) {
        for (const table of this.Tables) {
          const item = {}
          item.meta = '表'
          item.caption = table.Name
          item.value = table.Name
          item.score = 150
          data.push(item)
          for (const column of table.Columns) {
            if (columns.indexOf(column.Name) >= 0) {
              continue
            }
            columns.push(column.Name)
          }
        }
      }
      for (const column of columns) {
        const item = {}
        item.meta = '列'
        item.caption = column
        item.value = column
        item.score = 120
        data.push(item)
      }
      return data
    },
    columns() {
      if (this.SelectTable) {
        return this.findColumns(this.SelectTable)
      }
      return []
    }
  },
  mounted() {
    this.getDetail()
  },
  methods: {
    findColumns(t) {
      for (const table of this.Tables) {
        if (table.Name === t) {
          return table.Columns
        }
      }
      return []
    },
    beautifulSql() {
      let sql = this.$refs.ace.$ace.getValue()
      sql = sqlFormatter.format(sql)
      this.$refs.ace.$ace.setValue(sql)
    },
    beautifulCountSql() {
      let sql = this.$refs.ace2.$ace.getValue()
      sql = sqlFormatter.format(sql)
      this.$refs.ace2.$ace.setValue(sql)
    },
    changeDb() {
      if (!this.form.DbId) {
        return
      }
      apolloClient.query({
        fetchPolicy: 'network-only',
        query: gql`query ($id: String!) {
                    dbTables(DbId: $id){
                        Name
                        Columns{
                            Name
                            Remark
                        }
                    }
                }`,
        variables: { id: this.form.DbId }
      }).then(response => {
        if (response.data) {
          if (response.data.dbTables) {
            this.Tables = response.data.dbTables || []
          }
        } else {
          this.$notify.error(response.errors[0].message)
        }
      }).catch((err) => {
        this.$notify.error(err.message)
      })
    },
    getDetail() {
      apolloClient.query({
        fetchPolicy: 'network-only',
        query: gql`query ($reportId: String!) {
                    dictCategorySql(dictCategoryId: $reportId){
                        AllSql
                        DictionarySqlId
                        FilterSql
                        Remarks
                        DbId
                    }
                    reportDbList{
                        ReportDbId
                        Name
                    }
                }`,
        variables: { reportId: this.id }
      }).then(response => {
        if (response.data) {
          if (response.data.dictCategorySql) {
            this.form.DbId = response.data.dictCategorySql.DbId
            this.form.DictionarySqlId = response.data.dictCategorySql.DictionarySqlId
            this.form.FilterSql = response.data.dictCategorySql.FilterSql
            this.form.AllSql = response.data.dictCategorySql.AllSql
            this.form.Remarks = response.data.dictCategorySql.Remarks
            this.form.DbId = response.data.dictCategorySql.DbId
            this.$refs.ace.$ace.setValue(this.form.AllSql || '')
            this.$refs.ace2.$ace.setValue(this.form.FilterSql || '')
          }
          if (response.data.reportDbList) {
            this.DbList = response.data.reportDbList
          }
          this.changeDb()
        } else {
          this.$notify.error(response.errors[0].message)
        }
      }).catch((err) => {
        console.log(err)
        this.$notify.error(err.message)
      })
    },
    // 保存数据
    save() {
      this.form.Sql = this.$refs.ace.$ace.getValue()
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          var postData = {}
          postData.DictionaryCategoryId = this.id
          postData.DictionarySqlId = this.form.DictionarySqlId
          postData.AllSql = this.form.AllSql
          postData.FilterSql = this.form.FilterSql
          postData.DbId = this.form.DbId
          postData.Remarks = this.form.Remarks
          apolloClient.mutate({
            mutation: gql`mutation ($req: DictCategoryUpdateReq!) {
                            updateDictCategorySql(Req: $req)
                        }`,
            variables: { req: postData }
          }).then(response => {
            console.log(response)
            if (response.data.updateDictCategorySql) {
              this.$notify.success('保存成功')
              this.close()
            } else {
              this.$notify.error(response.errors[0].message)
            }
          }).catch((err) => {
            this.$notify.error(err.message)
          })
        }
      })
    },
    close() {
      this.$router.go(-1)
    }
  }
}
</script>

<style scoped>
</style>
